package com.kyzh.core.pager.me

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gushenge.atools.util.AView
import com.gushenge.core.base.Base
import com.gushenge.core.beans.Nav
import com.gushenge.core.beans.UserCenterBean
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.requests.UserRequest
import com.kyzh.core.R
import com.kyzh.core.activities.*
import com.kyzh.core.adapters.NavAdapter
import com.kyzh.core.databinding.FragMeV32Binding
import com.kyzh.core.databinding.FragMeV3TopDetailBinding
import com.gushenge.core.base.fragment.BaseFragment
import com.kyzh.core.utils.*
import com.kyzh.core.pager.weal.vip.OpenVipActivity
import com.kyzh.core.databinding.ItemMeFragmentTopBinding
import com.kyzh.core.download.down.DownActivity
import com.kyzh.core.pager.login.LoginActivity
import com.kyzh.core.pager.me.user.UserDataActivity
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMUserFullInfo
import org.jetbrains.anko.support.v4.startActivity


class MeFragment : BaseFragment() {

    private val adapter = Adapter()
    private lateinit var binding: FragMeV32Binding
    private lateinit var header: ItemMeFragmentTopBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.frag_me_v3_2, container, false)
        binding.lifecycleOwner = this
        header = ItemMeFragmentTopBinding.inflate(inflater)
        header.lifecycleOwner = this
        AView.setMargins(binding.rev, 0, AView.getStatusBarHeight(requireActivity()), 0, 0)

        header.proxy = Proxy()
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        header.apply {
            download.setOnClickListener {
                startActivity<DownActivity>()
            }
            header.setOnClickListener {
                if (startLogin()) {
                    startActivity<UserDataActivity>()
                }
            }
            info1.root.setOnClickListener {
                startActivity<MyCouponActivity>()
            }

            info2.root.setOnClickListener {
                startActivity<PointsMallActivity>()
            }

            info3.root.setOnClickListener {
                if (startLogin()) {
                    startActivity<BrowserActivity>(
                        GlobalKeys.TITLE to getString(R.string.ptbRecharge),
                        GlobalKeys.LINK to "${Base.BASEURLV3}/?ct=coin&uid=${MMKVConsts.uid}&t=$time&sign=${
                            httpSign(MMKVConsts.uid)
                        }"
                    )
                }
            }
        }
        binding.rev.adapter = adapter
        adapter.removeAllHeaderView()
        adapter.addHeaderView(header.root)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        initData()
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    fun initData() {
        UserRequest.getUserCenter {
            if (this == null) {
                MMKVConsts.uid = ""
                startActivity<LoginActivity>()
                return@getUserCenter
            }
            this.apply {
                val data = this

                header.apply {
                    userdata = data

                    name.post {
                        name.setShader(data.user.color)
                    }
                    if (data.user.isHuiyuan) {
                        tvVip.text = "VIP${data.user.vip}"
                        tvVip.setTextColor(Color.WHITE)
                    } else {
                        tvVip.text = "VIP未开通"
                        tvVip.setTextColor(Color.parseColor("#FF726A"))
                    }

                    info1.setInfo("卡券", data.user.coupon)
                    info2.setInfo("平台积分", data.user.point)
                    info4.setInfo("预约游戏", data.user.yuyue)
                    info3.setInfo(getString(R.string.ptb), data.user.coin)
                    adapter.setNewInstance(data.nav)

                    val v2TIMUserFullInfo = V2TIMUserFullInfo()
                    v2TIMUserFullInfo.setNickname(data.user.userName)
                    v2TIMUserFullInfo.faceUrl = data.user.face
                    //设置用户资料
                    V2TIMManager.getInstance().setSelfInfo(v2TIMUserFullInfo, object : V2TIMCallback {
                        override fun onSuccess() {
                            Log.e("User", "onSuccess: 用户信息设置成功 ")
                        }

                        override fun onError(p0: Int, p1: String?) {
                            Log.e("User", "onSuccess: 用户信息设置失败  $p0   $p1")
                        }
                    })
                    //省钱卡
                    if (data.shengqianka.shengqianka) {
                        ivOpenKa.text = "还有${data.shengqianka.day}天到期"
                    } else {
                        ivOpenKa.text = "未开通"
                    }
                    // 会员区
                    if (!data.huiyuan.isHuiyuan) {
                        ivOpenVip.text = "未开通"
                    }
                    progress.setMax(data.huiyuan.lastExp.toInt())
                    progress.progress = data.huiyuan.exp.toInt() % data.huiyuan.lastExp.toInt()
                    tvHuiYuanJinDu.text = "成长值 ${data.huiyuan.exp} / ${data.huiyuan.lastExp}"
                    tvHuiYuanBottom.text =
                        "距离下一级还需要 ${data.huiyuan.lastExp.toInt() - data.huiyuan.exp.toInt()} 成长值"
                }
            }
        }
    }


    private inner class Adapter : BaseQuickAdapter<UserCenterBean.NavX, BaseViewHolder>(R.layout.item_me_nav) {
        override fun convert(holder: BaseViewHolder, item: UserCenterBean.NavX) {
            holder.setText(R.id.tvTitle, item.title)
            val rev = holder.getView<RecyclerView>(R.id.rev)
            rev.layoutManager = object : GridLayoutManager(requireContext(), 4) {
                override fun canScrollHorizontally(): Boolean {
                    return false
                }

                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            if (!item.data.isNullOrEmpty()) {
                if (item.title == "热门游戏") {
                    rev.adapter = NavAdapter(R.layout.item_frag_me1_function, item.data)
                } else if (item.title == "服务") {
                    val navItem = Nav()
                    navItem.name = "GM后台"
                    navItem.type = 888
                    navItem.icon = "${Base.BASEURL}/static/app3/20220823/nav_2_8.png"
                    navItem.login = 1
                    navItem.url = ""
                    item.data.add(navItem)
                    rev.adapter = NavAdapter(R.layout.item_frag_me_new, item.data)
                } else {
                    rev.adapter = NavAdapter(R.layout.item_frag_me_new, item.data)
                }
            }
        }
    }

    private fun FragMeV3TopDetailBinding.setInfo(title1: String, info1: String) {
        this.title = title1
        this.info = info1
    }

    inner class Proxy {
        fun goMessage() {
            if (startLogin()) {
                startActivity<NoticeActivity>()
            }
        }

        fun sign() {
            if (startLogin()) {
                context?.navClickByLogin(Nav(login = 1, type = 321))
            }
        }

        fun openShengQianKa() {
            if (startLogin()) {
                startActivity<BaseFragmentActivity>(GlobalKeys.TYPE to BaseFragmentActivity.MONEYCARD)
            }
        }

        fun openHuiYuan() {
            if (startLogin()) {
                OpenVipActivity.start(requireContext())
            }

        }
    }
}